package com.Demo;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.Scanner;

public class Demo01_insert {
    public static void main(String[] args) {
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/test?useSSL" +
                "=false&serverTimezone=UTC");
        mysqlDataSource.setUser("root");
        mysqlDataSource.setPassword("237912");
        DataSource dataSource = mysqlDataSource;

        Connection connection = null;
        PreparedStatement statement = null;

        try {
            connection = dataSource.getConnection();
            String sql = "insert into student (name, sno, age, gender, enroll_data, class_id) " +
                    "values (?, ?, ?, ?, ?, ?)";

            statement = connection.prepareStatement(sql);
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入要增添的名字：");
            String inputName = scanner.next();
            System.out.println("请输入要增添的学号：");
            String inputSno = scanner.next();
            System.out.println("请输入要增添的年龄：");
            int inputAge = scanner.nextInt();
            System.out.println("请输入要增添的性别：");
            byte inputGender = scanner.nextByte();
            System.out.println("请输入要增添的入学日期：");
            String inputEnrollData = scanner.next();
            System.out.println("请输入要增添的班级编号：");
            long inputClass_Id = scanner.nextLong();

            statement.setString(1, inputName);
            statement.setString(2, inputSno);
            statement.setInt(3, inputAge);
            statement.setByte(4, inputGender);
            statement.setString(5, inputEnrollData);
            statement.setLong(6, inputClass_Id);
            System.out.println();
            int row = statement.executeUpdate();
            if (row == 1) {
                System.out.println("插入成功");
            } else {
                System.out.println("插入失败");
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }


    }
}
